#include "StdAfx.h"
#include "TxtFileLoader.h"
#include <stdio.h>
#include <io.h>

CTxtFileLoader::CTxtFileLoader(void)
{
	m_pFileBuf = NULL;
	m_nPageSize = 500;
	m_nOldPageSize = m_nPageSize;
	m_nStep = 100;
	m_bForward = TRUE;
}

CTxtFileLoader::~CTxtFileLoader(void)
{
	if (m_pFileBuf != NULL)
	{
		delete []m_pFileBuf;
	}
}

bool CTxtFileLoader::LoadFile( LPCTSTR pszFileName )
{
	if (0 == pszFileName)
	{
		return false;
	}
	
	DWORD dwErr = 0;
	HANDLE hFile = CreateFile(pszFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);
	if ( INVALID_HANDLE_VALUE == hFile)
	{
		dwErr = GetLastError();
		return false;
	}

	DWORD dwHight = 0;
	DWORD dwLength = GetFileSize(hFile, &dwHight);
	if (dwLength > 0)
	{
		char *pBuf = NULL;
		pBuf = new char[dwLength];
		DWORD dwReadedBytes = 0;

		if (!ReadFile(hFile, (void*)pBuf, dwLength, &dwReadedBytes, NULL))
		{
			dwErr = GetLastError();
		}
		
		CloseHandle(hFile);

		int opt = IS_TEXT_UNICODE_UNICODE_MASK;
		if (!IsTextUnicode(pBuf, dwLength, &opt))
		{
			int nwcharCount = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pBuf, -1, NULL, 0);
			m_pFileBuf = new wchar_t[nwcharCount];
			m_nBufSize = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pBuf, dwLength, m_pFileBuf, nwcharCount);
		}

		m_pCurPageBufStart = m_pFileBuf;
		m_nCurPageSize = m_nPageSize > m_nBufSize ? m_nBufSize : m_nPageSize;

		delete []pBuf;
	}
	
	return true;
}

void CTxtFileLoader::NextPage()
{
	if (m_pCurPageBufStart + m_nCurPageSize >= m_pFileBuf + m_nBufSize)
	{
		return;
	}

	int nLeftSize = m_nBufSize - (m_pCurPageBufStart - m_pFileBuf) / sizeof(wchar_t);
	m_pCurPageBufStart += m_nCurPageSize;
	if (m_nCurPageSize > nLeftSize)
	{
		m_nCurPageSize = nLeftSize;
	}
	
	m_pCurPageBufEnd = m_pCurPageBufStart + m_nCurPageSize;
}

void CTxtFileLoader::PrePage()
{
	if (m_pCurPageBufStart <= m_pFileBuf)
	{
		return;
	}

	int nPreSize = (m_pCurPageBufStart - m_pFileBuf) / sizeof(wchar_t);
	if (nPreSize < m_nCurPageSize)
	{
		m_nCurPageSize = m_nPageSize;
	}
	
	m_pCurPageBufStart = m_pCurPageBufStart - m_nCurPageSize;
	if (m_pCurPageBufStart <= m_pFileBuf)
	{
		m_pCurPageBufStart = m_pFileBuf;
	}

	//m_pCurPageBufEnd -= m_nCurPageSize; 
}

void CTxtFileLoader::ResizePage( int& nLength, int &nStep)
{
	m_nCurPageSize += nStep;
	if (m_nCurPageSize <= 0)
	{
		m_nCurPageSize = 1;
	}

	nLength = m_nCurPageSize;
}

void CTxtFileLoader::GetCurPage( wchar_t **ppBuf, int& nLength )
{
	*ppBuf = m_pCurPageBufStart;
	nLength = m_nCurPageSize;
}
